<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model= "name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number= "age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model= "sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click= 'changeAddItem'>添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="index">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="delFn(item.index)">删除</button>
            <button @click="copyreader(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
import { watch } from 'vue'
export default {
  data(){
    return{
    falg:false,
      i:'',
    name:'',
    age:'',
    sex:'',
    list:JSON.parse(localStorage.getItem('List'))||[]  // 从本地取出数据
    }
  },
  methods:{
    // 添加按钮
    changeAddItem(){
      // 判断不能为空
      if(this.name.length===0||this.age.length==0 ){
        return alert('不能为空')
      } 
      // 全局的falg 为false 则为修改按钮 反之则为添加
      if(this.falg){
      this.list[this.i].name=this.name
      this.list[this.i].age=this.age
      this.list[this.i].sex=this.sex
      } else {
        // 添加事件
      this.list.push({
        index:this.list.length>0?this.list[this.list.length-1].index+1:1,
        name:this.name,
         age:this.age,
         sex:this.sex
        })
        // 清空输入框
        this.name=''
        this.age=''
        this.sex=''
      }
     
    },
    // 删除事件
    delFn(id){
      this.list.splice(id,1)
    },
    // 编辑事件
    copyreader(index){
      // 编辑时把值赋给输入框 让添加按钮为修改按钮
      this.falg=true
      this.i=index
      this.name=this.list[index].name
      this.age=this.list[index].age
      this.sex=this.list[index].sex
    },
    
  },
  // 深度监视list 的数据
  watch:{
    list:{
      deep:true,
      handler(){
        // 把数据保存本地
        localStorage.setItem('List', JSON.stringify(this.list))
      }
    }
  }
}
</script>